package com.redwine.app;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.AddressListResponse;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.DownOptionsBean;
import com.redwine.app.net.responses.ProvinceDataResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.DimenUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.view.CommonPopupListWindow;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 添加收货地址
 * 作者：gassion on 17/9/9 16:11
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class ShippingAddressAddActivity extends BaseActivity {

    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    @ViewInject(R.id.address_add_et_name)
    private EditText mAddressAddEtName;
    @ViewInject(R.id.address_add_et_phone)
    private EditText mAddressAddEtPhone;
    @ViewInject(R.id.address_add_et_address)
    private EditText mAddressAddEtAddress;
    @ViewInject(R.id.address_add_tv_province)
    private TextView mAddressAddTvProvince;
    @ViewInject(R.id.address_add_tv_city)
    private TextView mAddressAddTvCity;
    @ViewInject(R.id.address_add_tv_area)
    private TextView mAddressAddTvArea;
    private AddressListResponse.DataEntity dataEntity;
    public static final String DATA_ENTITY = "DATA_ENTITY";
    private List<DownOptionsBean> responseDataCity;//省
    private List<DownOptionsBean> responseCityDataCity;//城市
    private List<DownOptionsBean> responseAreaDataCity;//区
    private String mProvinceId;
    private String mCityId;
    private String mAreaId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shipping_address_add);
        ViewUtils.inject(this);
        initView();
        requestProvinceData();
    }

    private void initView() {
        layoutBack.setVisibility(View.VISIBLE);
        final Intent intent = getIntent();
        if (null != intent) {
            dataEntity = (AddressListResponse.DataEntity) intent.getSerializableExtra(DATA_ENTITY);
        }
        if (null != dataEntity) {
            headerTitle.setText(R.string.shipping_address_update_address);
            mAddressAddEtName.setText(dataEntity.getName());
            mAddressAddEtPhone.setText(dataEntity.getTel());
            mAddressAddEtAddress.setText(dataEntity.getAddress());
            mAddressAddTvProvince.setText(dataEntity.getProvince());
            mAddressAddTvCity.setText(dataEntity.getCity());
            mAddressAddTvArea.setText(dataEntity.getArea());
            mProvinceId = dataEntity.getProvince_id();
            mCityId = dataEntity.getCity_id();
            mAreaId = dataEntity.getArea_id();
            requestCityData(dataEntity.getProvince_code());
            requestAreaData(dataEntity.getCity_code());
        } else {
            headerTitle.setText(R.string.shipping_address_add);
        }
    }

    @OnClick({R.id.layout_back, R.id.address_add_tv_province, R.id.address_add_tv_city, R.id.address_add_tv_area, R.id.address_add_tv_save})
    public void mClick(View v) {
        switch (v.getId()) {

            case R.id.layout_back:
                finish();
                break;

            case R.id.address_add_tv_province:
                showDownOptions(mAddressAddTvProvince, responseDataCity);
                break;

            case R.id.address_add_tv_city:
                showDownOptions(mAddressAddTvCity, responseCityDataCity);
                break;

            case R.id.address_add_tv_area:
                showDownOptions(mAddressAddTvArea, responseAreaDataCity);
                break;

            case R.id.address_add_tv_save:
                submit();
                break;


        }
    }


    /**
     * 提交数据
     */
    private void submit() {
        String name = mAddressAddEtName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "收货姓名不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        String phone = mAddressAddEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "电话号码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mProvinceId)) {
            Toast.makeText(this, "请选择省份", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mCityId)) {
            Toast.makeText(this, "请选择城市", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mAreaId)) {
            Toast.makeText(this, "请选择区县", Toast.LENGTH_SHORT).show();
            return;
        }

        String address = mAddressAddEtAddress.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            Toast.makeText(this, "详细地址不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        showWaiting();

        String url;
        Map<String, String> params = new LinkedHashMap<>();
        if (null != dataEntity && !TextUtils.isEmpty(dataEntity.getId())) {
            params.put("address_id", dataEntity.getId());
            url = NetworkConstants.ADDRESS_SAVE_URL;
        } else {
            url = NetworkConstants.ADD_ADDRESS_URL;
        }
        params.put("tel", phone);
        params.put("name", name);
        params.put("address", address);
        params.put("province", mProvinceId);
        params.put("city", mCityId);
        params.put("area", mAreaId);
        params.put("uid", Global.user.getUid());
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissWaiting();
                showToast(response.getMsg());
                if (response.isSuccess()) {
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_SHIPPING_ADDRESS));
                    finish();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);

    }

    /**
     * 获取省
     */
    private void requestProvinceData() {
        showWaiting();
        String url = NetworkConstants.GET_PROVINCE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<ProvinceDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProvinceDataResponse.class, false, params, new Response.Listener<ProvinceDataResponse>() {
            @Override
            public void onResponse(ProvinceDataResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    ProvinceDataResponse.DataEntity responseData = response.getData();
                    responseDataCity = responseData.getCity();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 获取城市
     */
    private void requestCityData(String provinceCode) {
        showWaiting();
        String url = NetworkConstants.GET_CITY_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("province_code", provinceCode);
        GsonRequest<ProvinceDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProvinceDataResponse.class, false, params, new Response.Listener<ProvinceDataResponse>() {
            @Override
            public void onResponse(ProvinceDataResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    ProvinceDataResponse.DataEntity responseData = response.getData();
                    responseCityDataCity = responseData.getCity();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 获取区
     */
    private void requestAreaData(String provinceCode) {
        showWaiting();
        String url = NetworkConstants.GET_AREA_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("city_code", provinceCode);
        GsonRequest<ProvinceDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProvinceDataResponse.class, false, params, new Response.Listener<ProvinceDataResponse>() {
            @Override
            public void onResponse(ProvinceDataResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    ProvinceDataResponse.DataEntity responseData = response.getData();
                    responseAreaDataCity = responseData.getCity();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(R.string.generic_check);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 显示下拉选项
     *
     * @param textView
     */
    private void showDownOptions(final TextView textView, final List<DownOptionsBean> cityEntitys) {
        if (null != cityEntitys && !cityEntitys.isEmpty()) {
            CommonPopupListWindow popupListWindow = new CommonPopupListWindow(this, cityEntitys);
            popupListWindow.setOnClickListener(new CommonPopupListWindow.OnClickListener() {
                @Override
                public void onClick(int position) {
                    if (textView.equals(mAddressAddTvProvince)) {
                        mProvinceId = cityEntitys.get(position).getId();
                        requestCityData(cityEntitys.get(position).getCode());
                    } else if (textView.equals(mAddressAddTvCity)) {
                        mCityId = cityEntitys.get(position).getId();
                        requestAreaData(cityEntitys.get(position).getCode());
                    } else {
                        mAreaId = cityEntitys.get(position).getId();
                    }
                    textView.setText(cityEntitys.get(position).getName());
                }
            });
            popupListWindow.showAsDropDown(textView, 0, DimenUtils.dip2px(8));
        }
    }
}
